package com.cuhk.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.cuhk.common.constant.RedisKeyConstant;
import com.cuhk.common.exception.BizCodeEnum;
import com.cuhk.common.utils.R;
import com.cuhk.gulimall.auth.feign.MemberFeignService;
import com.cuhk.gulimall.auth.feign.ThirdPartyFeignService;
import com.cuhk.gulimall.auth.vo.UserLoginVo;
import com.cuhk.gulimall.auth.vo.UserRegisterVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    static final long SMS_CODE_TIMEOUT = 360000;

    @GetMapping(value = "/login.html")
    public String loginPage(Model model) {
        return "login";
    }

    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phoneNumber) {
        // 防止相同手机号在60s内多次调用验证码发送接口
        String already = redisTemplate.opsForValue().get(RedisKeyConstant.SMS_CODE_PREFIX + phoneNumber);
        if(already != null) {
            return R.error(BizCodeEnum.SMS_TOO_SOON_EXCEPTION.getCode(), BizCodeEnum.SMS_TOO_SOON_EXCEPTION.getMessage());
        }
        // Redis缓存验证码
        R res = thirdPartyFeignService.sendSms(phoneNumber, "112233");
        if(res.get("code").equals(0)) {
            redisTemplate.opsForValue().set(RedisKeyConstant.SMS_CODE_PREFIX + phoneNumber, "112233", SMS_CODE_TIMEOUT, TimeUnit.MILLISECONDS);
            return res;
        }
        else {
            return R.error(BizCodeEnum.SMS_FAIL_SEND.getCode(), BizCodeEnum.SMS_FAIL_SEND.getMessage());
        }
    }

    @PostMapping("/register-member")
    public String register(@Valid UserRegisterVo userRegisterVo, BindingResult bindingResult,
                           RedirectAttributes redirectAttributes) {
        if(bindingResult.hasErrors()) {
            Map<String, String> errors = bindingResult.getFieldErrors().
                    stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
            // 用户填写信息没有通过基本格式验证，返回验证页面
            return "redirect:http://localhost:6060/register.html";
        }
        // 检查验证码是否过期
        String smsCode = redisTemplate.opsForValue().get(RedisKeyConstant.SMS_CODE_PREFIX + userRegisterVo.getPhoneNumber());
        if(StringUtils.isEmpty(smsCode)) {
            // 验证码过期了
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码过期了");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://localhost:6060/register.html";
        }
        else if(!smsCode.equals(userRegisterVo.getVerificationCode())) {
            // 验证码填写不正确
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码填写有误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://localhost:6060/register.html";
        }
        else {
            // 调用远程服务存储用户
            R registerResult = memberFeignService.saveMember(userRegisterVo);
            if(registerResult.get("code").equals(0)) {
                return "redirect:http://localhost:6060/login.html";
            }
            else {
                Map<String, String> errors = new HashMap<>();
                errors.put("msg", registerResult.getData(new TypeReference<String>(){}));
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://localhost:6060/register.html";
            }
        }
        // return "redirect:http://localhost:6060/login.html";
    }

    @PostMapping("/login-member")
    public String login(@RequestParam @Valid UserLoginVo userLoginVo, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
        if(bindingResult.hasErrors()) {
            Map<String, String> validationErrors = bindingResult.getFieldErrors().
                    stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", validationErrors);
            return "redirect:http://localhost:6060/login.html";
        }
        else {
            R loginResult = memberFeignService.loginMember(userLoginVo);
            if(loginResult.get("code").equals(0)) {
                return "redirect:http://localhost:12000/index.html";
            }
            else {
                Map<String, String> errors = new HashMap<>();
                errors.put("msg", loginResult.getData(new TypeReference<String>(){}));
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://localhost:6060/login.html";
            }
        }
    }

}
